package logic

import (
	"context"
	"xialou_platform/app/errorx"
	"xialou_platform/app/requestx"
	"xialou_platform/app/respx"
	"xialou_platform/services/agent/rpc/agentClient"

	"xialou_platform/services/agent/api/internal/svc"
	"xialou_platform/services/agent/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type AgentRateLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewAgentRateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AgentRateLogic {
	return &AgentRateLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *AgentRateLogic) AgentRate(req *types.AgentRateReq) error {
	uid, err := requestx.FetchUserIdByJwt(l.ctx)
	if err != nil {
		return err
	}
	agentParam, err := l.svcCtx.AgentRpc.AgentById(l.ctx, &agentClient.IdBody{Id: uid})
	if err != nil {
		return errorx.NewMsgCodeError(errorx.UnLoginCode, "请重新登录")
	}
	if agentParam.Type != 3 || agentParam.Status != 2 {
		return errorx.NewDefaultError("你不是代理商，没有权限！")
	}
	if req.ProfitRate < 30 || req.ProfitRate > 50 {
		return errorx.NewDefaultError("利润率设置范围：30-50")
	}
	_, err = l.svcCtx.AgentRpc.AgentRate(l.ctx, &agentClient.AgentRateReq{
		Type:       req.Type,
		Id:         respx.IDParse(req.Id).GetInt64(),
		ProfitRate: req.ProfitRate,
		TopUid:     agentParam.Id,
	})
	if err != nil {
		return err
	}
	return nil
}
